package com.lottery.material.handler;

import com.lottery.material.common.JsonResult;
import com.lottery.material.common.ResultVO;
import com.lottery.material.exception.ResponseException;
import com.lottery.material.utils.ResultVOUtil;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Description：异常处理
 * Created by 朱正磊 on 2019-04-09 11:20
 */
@ControllerAdvice
public class MyExceptionHandler {

    /**
     * description：拦截自定义异常，响应json格式数据
     * user 朱正磊
     * time 2019-04-09 11:29
     * @param e 异常对象
     * @return 返回响应对象
     */
    @ExceptionHandler(value = ResponseException.class)
    @ResponseBody
    public ResultVO handlerResponseException(ResponseException e) {
        return ResultVOUtil.error(e.getCode(), e.getMessage());
    }

    /**
     * description：拦截MVC参数绑定异常，响应json格式数据
     * user 朱正磊
     * time 2019-04-09 11:29
     * @param e 异常对象
     * @return 返回响应对象
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public JsonResult handlerBindException(BindException e) {
        List<ObjectError> allErrors = e.getAllErrors();
        return JsonResult.failure(400, allErrors.get(0).getDefaultMessage());
    }

}
